/**
 * @returns {String} 当前浏览器名称
 */
export const getExplorer = () => {
  const ua = window.navigator.userAgent
  const isExplorer = (exp) => {
    return ua.indexOf(exp) > -1
  }
  if (isExplorer('MSIE')) return 'IE'
  else if (isExplorer('Firefox')) return 'Firefox'
  else if (isExplorer('Chrome')) return 'Chrome'
  else if (isExplorer('Opera')) return 'Opera'
  else if (isExplorer('Safari')) return 'Safari'
}
/**
 * 把关系数组过滤成树形数据
 * @param data  原始数据
 * @param children_key  孩子的键名/默认是children
 * @param id_key  id的键名/默认是id
 * @param pid_key 储存上级的键名/默认pid
 * @returns {Array} 组装后的数据
 */
export const toTree = (data, children_key, id_key, pid_key) => {
  let child_key = children_key || 'children'
  let id = id_key || 'id'
  let pid = pid_key || 'pid'
  data.forEach(function (item) {
    delete item[child_key]
  })
  let map = {}
  data.forEach(function (item) {
    map[item[id]] = item
  })
  let val = []
  data.forEach(function (item) {
    let parent = map[item[pid]]
    if (parent) {
      (parent[child_key] || (parent[child_key] = [])).push(item)
    } else {
      val.push(item)
    }
  })
  return val
}
/**
 * 递归遍历树形结构数据
 * @param arr 要遍历的数组，遍历之后会直接更改这个数据
 * @param value 判断的值
 * @param id_key  用那个键值判断/默认id
 * @param update_key 需要更改的键值
 * @param update_value  需要更改的内容
 * @param child_key 树形结构孩子的键值
 */
export const treeFind = (arr, value, id_key, update_key, update_value, child_key) => {
  let id = id_key || 'id'
  child_key = child_key || 'children'
  if (update_key === '' || update_key === undefined || update_key === null) {
    console.log('调用treeFind方法【update_key】必须传递')
    return false
  }
  arr.forEach((item) => {
    if (item[id] === value) {
      item[update_key] = update_value
      return true
    } else if (item[child_key] && item[child_key].length > 0) {
      treeFind(item[child_key], value, id_key, update_key, update_value, child_key)
    }
  })
}
